package com.rent.auth.service.impl;

import com.rent.auth.model.Admin;
import com.rent.auth.pojo.AdminExtension;
import com.rent.auth.pojo.AdminUserDetails;
import com.rent.auth.service.IAdminService;
import com.rent.common.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.oauth2.provider.ClientDetails;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Collection;


/*****
 * 自定义授权认证类
 */
@Slf4j
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    ClientDetailsService clientDetailsService;

    @Autowired
    private IAdminService adminService;

    /****
     * 自定义授权认证
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        log.info("认证名称" + username);
        //取出身份，如果身份为空说明没有认证
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        log.info("认证信息authentication:{}", authentication);
        //没有认证统一采用httpbasic认证，httpbasic中存储了client_id和client_secret，开始认证client_id和client_secret
        if (authentication == null) {
            ClientDetails clientDetails = clientDetailsService.loadClientByClientId(username);
            if (clientDetails != null) {
                //秘钥
                String clientSecret = clientDetails.getClientSecret();
                //数据库查找方式
                return new User(username, clientSecret, AuthorityUtils.commaSeparatedStringToAuthorityList(""));
            }
        }
        HttpServletRequest request = ((ServletRequestAttributes) (RequestContextHolder.currentRequestAttributes())).getRequest();
        // 逻辑处理
        String tenant = request.getParameter("tenant");
        String loginName = request.getParameter("username");
        log.info("获取公司代码:{}用户:{}", tenant, loginName);
        if (StringUtils.isEmpty(loginName)) return null;
        AdminUserDetails userDetails = adminService.loadUserByUsernameWithTenant(loginName, tenant);
        if (userDetails == null) return null;
        Admin admin = userDetails.getAdmin();
        //根据用户名查询用户信息
        if (admin == null) return null;
        String pwd = admin.getPassword();
        // 权限
        String permission = "1";
        if (admin.getIsMax() == null || admin.getIsMax() != 1) {
            permission = "0";
        }
        Collection<GrantedAuthority> authorities = AuthorityUtils.commaSeparatedStringToAuthorityList(permission);
        // 添加角色
        if (!CollectionUtils.isEmpty(userDetails.getAuthorities())) {
            authorities.addAll(userDetails.getAuthorities());
        }
        //创建User对象  授予权限角色 权限
        AdminExtension model = new AdminExtension(loginName, pwd, authorities);
        model.setTenant(tenant);
        model.setId(admin.getId());
        model.setUsername(loginName);
        model.setRoleId(admin.getRole());
        model.setStatus(admin.getStatus());
        model.setPermissionList(userDetails.getPermissionList());
        return model;
    }


}
